<template>
  <div class="traceability-list">
    <!-- 页面标题和面包屑 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon">
          <Document />
        </el-icon>
        <h1>溯源管理</h1>
      </div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>企业管理</el-breadcrumb-item>
        <el-breadcrumb-item>溯源管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>



    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" @click="addNew" class="add-btn">
            <el-icon>
              <Plus />
            </el-icon>
            新增商品
          </el-button>
          <el-button type="danger" @click="batchDelete" class="delete-btn">
            <el-icon>
              <Delete />
            </el-icon>
            批量删除
          </el-button>

        </div>
        <div class="toolbar-right">
          <el-button @click="refreshData" :loading="loading" class="refresh-btn">
            <el-icon>
              <Refresh />
            </el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">

      <el-table :data="tableData" row-key="id" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="commodityName" label="商品名称" width="120" />
        <el-table-column prop="productionBatch" label="成产批次" width="120" />
        <el-table-column prop="shelfLife" label="保质期(天)" width="120" />
        <el-table-column prop="licenseNumber" label="生产许可证号" width="200" />
        <el-table-column prop="productionEnterprises" label="生产企业" width="200" />
        <el-table-column prop="informationPerfection" label="信息完善度" width="120">
          <template #default="scond">
            <span v-if="scond.row.informationPerfection != 100" style="color:red;">{{ scond.row.informationPerfection + "%"
              }}</span>
            <span v-else style="color: green;">{{ scond.row.informationPerfection + "%" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createUserName" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="270">
          <template #default="scond">
            {{ moment(scond.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="updateUserName" label="修改人" width="120" />
        <el-table-column prop="updateTime" label="修改时间" width="270">
          <template #default="scond">


            <span v-if="scond.row.updateTime != null">{{ moment(scond.row.updateTime).format("YYYY-MM-DD HH:mm:ss")
              }}</span>


          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="420">
          <template #default="scond">
            <el-button type="primary" size="small" @click="detail(scond.row)">详情</el-button>
            <el-button type="primary" size="small" @click="updTrace(scond.row)">修改</el-button>
            <el-button type="primary" size="small" @click="exportCode(scond.row.id)">导出溯源码</el-button>
            <el-button type="primary" size="small" @click="delTrace(scond.row)">删除</el-button>
            <el-button type="primary" size="small" @click="getInformationPerfection(scond.row)">刷新信息完善度</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-left">


          <span class="total-info">共 {{ page.totalCount }} 条记录</span>
        </div>
        <div class="pagination-right">
          <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :total="page.totalCount" :page-sizes="[5, 10, 15, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" />
        </div>
      </div>
    </el-card>

    <!-- 新增对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :close-on-click-modal="false">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">

        <el-form-item label="商品名称" prop="commodityId">
          <el-select v-model="ruleForm.commodityId" placeholder="请选择">

            <el-option v-for="value in commodity" :label="value.commodityName" :value="value.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="成产批次" prop="productionBatch">
          <el-input v-model="ruleForm.productionBatch" />
        </el-form-item>

        <el-form-item label="保质期(天)" prop="shelfLife">
          <el-input v-model="ruleForm.shelfLife" />
        </el-form-item>

        <el-form-item label="成产许可证号" prop="licenseNumber">
          <el-input v-model="ruleForm.licenseNumber" />
        </el-form-item>

        <el-form-item label="成产企业" prop="productionEnterprises">
          <el-input v-model="ruleForm.productionEnterprises" />
        </el-form-item>

        <el-form-item label="封面图" prop="coverImage">
          <el-upload class="avatar-uploader" action="http://localhost:5073/api/Img/Images" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm.coverImage" :src="ruleForm.coverImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>





    <!-- 修改对话框 -->
    <el-dialog v-model="upddialogVisible" title="修改商品" width="700px" :close-on-click-modal="false">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">

        <el-form-item label="商品名称" prop="commodityId">
          <el-select v-model="ruleForm.commodityId" placeholder="请选择">

            <el-option v-for="value in commodity" :label="value.commodityName" :value="value.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="成产批次" prop="productionBatch">
          <el-input v-model="ruleForm.productionBatch" />
        </el-form-item>

        <el-form-item label="保质期(天)" prop="shelfLife">
          <el-input v-model="ruleForm.shelfLife" />
        </el-form-item>

        <el-form-item label="成产许可证号" prop="licenseNumber">
          <el-input v-model="ruleForm.licenseNumber" />
        </el-form-item>

        <el-form-item label="成产企业" prop="productionEnterprises">
          <el-input v-model="ruleForm.productionEnterprises" />
        </el-form-item>

        <el-form-item label="封面图" prop="coverImage">
          <el-upload class="avatar-uploader" action="http://localhost:5073/api/Img/Images" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm.coverImage" :src="ruleForm.coverImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="updsubmitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 溯源码预览对话框 -->
    <el-dialog v-model="exportDialogVisible" title="溯源码预览" width="640px" :close-on-click-modal="false">
      <div style="margin-bottom: 12px; line-height: 24px;">
        <div><b>溯源ID：</b>{{ exportPreview.id }}</div>
        <div><b>商品名称：</b>{{ exportPreview.commodityName }}</div>
        <div><b>生产批次：</b>{{ exportPreview.productionBatch }}</div>
      </div>
      <div
        style="display:flex; justify-content:center; align-items:center; padding: 12px; background:#fafafa; border:1px solid #eee; border-radius:6px;">
        <el-image v-if="exportPreview.barcodeImage" :src="exportPreview.barcodeImage" fit="contain"
          style="width: 560px; height: 180px;" />
        <div v-else style="color:#909399;">正在生成条形码...</div>
      </div>
    </el-dialog>


  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import {
  Delete,
  Download,
  Refresh,
  Search,
  Document,
  Box,
  Check,
  Warning,
  View,
  Edit
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import readhttp from '@/router/readhttp'
import axios from 'axios'
import { useCounterStore } from "@/stores/counter";
import wirlthttp from '@/router/wirlthttp'
import moment from 'moment'
var pinia = useCounterStore()
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs'
import router from '@/router'



// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const selectedRows = ref<any[]>([])
const dialogVisible = ref(false)
const upddialogVisible = ref(false)
const dialogTitle = ref('新增商品')
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 溯源码预览弹窗状态
const exportDialogVisible = ref(false)
const exportPreview = reactive({
  id: '',
  commodityName: '',
  productionBatch: '',
  barcodeImage: ''
})

//导出溯源码
const exportCode = (mid: any) => {
  // 显示加载状态
  ElMessage.info('正在生成溯源码，请稍候...')

  // 根据 id 从表格数据中获取名称与批次，先展示在弹窗
  const current: any = (tableData.value as any[]).find((x: any) => x.id === mid) || {}
  exportPreview.id = String(mid)
  exportPreview.commodityName = current.commodityName || ''
  exportPreview.productionBatch = current.productionBatch || ''
  exportPreview.barcodeImage = ''
  exportDialogVisible.value = true

  readhttp.post("/api/Read/ExportTrace", {
    traceId: mid,
    barcodeType: "CODE128", // 指定条形码类型，注意大写
    width: 800,
    height: 300
  }).then(res => {
    console.log(res.data)

    // 检查响应状态
    if (res.data.code !== 200) {
      ElMessage.error(res.data.message || '生成溯源码失败')
      return
    }

    // 从响应中提取数据
    const responseData = res.data.data
    if (!responseData) {
      ElMessage.error('数据为空')
      return
    }

    // 从响应中提取Base64图片数据
    const barcodeImage = responseData.barcodeImage
    if (!barcodeImage) {
      ElMessage.error('未获取到条形码图片数据')
      return
    }
    // 兼容是否带有 data url 前缀
    const hasPrefix = /^data:image\//.test(barcodeImage)
    exportPreview.barcodeImage = hasPrefix ? barcodeImage : `data:image/png;base64,${barcodeImage}`
    // 覆盖展示信息为后端返回的权威值
    if (responseData.commodityName) exportPreview.commodityName = responseData.commodityName
    if (responseData.productionBatch) exportPreview.productionBatch = responseData.productionBatch
    ElMessage.success('溯源码生成成功')
  })
}


//图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.coverImage = response.data;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

  return true
}




// 表单数据
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "traceId": null,
  /// <summary>
  /// 商品Id
  /// </summary>
  "commodityId": null,
  /// <summary>
  /// 生产批次
  /// </summary>
  "productionBatch": "",
  /// <summary>
  /// 保质期(天)
  /// </summary>
  "shelfLife": null,
  /// <summary>
  /// 生产许可证号
  /// </summary>
  "licenseNumber": "",
  /// <summary>
  /// 生产企业
  /// </summary>
  "productionEnterprises": "",
  /// <summary>
  /// 封面图
  /// </summary>
  "coverImage": "",
  /// <summary>
  /// 信息完善度
  /// </summary>
  "informationPerfection": 0,
  /// <summary>
  /// 产品资质报告
  /// </summary>
  "productQualifications": "",
  /// <summary>
  /// 创建人
  /// </summary>
  "createUser": pinia.login.userName,
  "number": null,
  UpdateUser: pinia.login.userName
})



const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  commodityId: [
    { required: true, message: '请选择商品名称', trigger: 'blur' },
  ],
  productionBatch: [
    {
      required: true,
      message: '请输入生产批次',
      trigger: 'blur',
    },
  ],
  shelfLife: [
    {
      required: true,
      message: '请输入保质期(天)',
      trigger: 'blur',
    },
  ],
  licenseNumber: [
    {

      required: true,
      message: '请输入生产许可证号',
      trigger: 'blur',
    },
  ],
  productionEnterprises: [
    {
      required: true,
      message: '请输入生产企业',
      trigger: 'blur',
    },
  ],
  coverImage: [
    {
      required: true,
      message: '请上传封面图',
      trigger: 'blur',
    },
  ],

})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      wirlthttp.post('api/Wirlt/AddTrace', ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          ruleForm.commodityId = null
          ruleForm.productionBatch = ""
          ruleForm.shelfLife = null
          ruleForm.licenseNumber = ""
          ruleForm.productionEnterprises = ""
          ruleForm.coverImage = ""
          dialogVisible.value = false
          listtrace();


        }
        else {
          ElMessage.error(res.data.message);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


//修改
const updsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      wirlthttp.post('api/Wirlt/UpdTrace', ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          ruleForm.commodityId = null
          ruleForm.productionBatch = ""
          ruleForm.shelfLife = null
          ruleForm.licenseNumber = ""
          ruleForm.productionEnterprises = ""
          ruleForm.coverImage = ""
          upddialogVisible.value = false
          
          listtrace();


        }
        else {
          ElMessage.error(res.data.message);
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}



//重置

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


// 模拟数据
const tableData = ref([])
const page = reactive({
  PageIndex: 1,
  PageSize: 5,
  "totalPage": 0,
  "totalCount": 0,
})

const listtrace = () => {
  readhttp.get('api/Read/ListTrace', {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize,
    }
  }).then(res => {
    tableData.value = res.data.pageDatas
    page.totalCount = res.data.totalCount
    page.totalPage = res.data.totalPage
  })
}

const commodity = ref([
  {
    "id": null,
    "commodityName": ""
  }
]);

const getcommodity = () => {
  readhttp.get('api/Read/GetCommodity', {}).then(res => {
    commodity.value = res.data.data
  })
}


watch(page, () => {
  listtrace();
  getcommodity();
})


//信息完善度
const getInformationPerfection = (row: any) => {
  readhttp.post('api/Read/GetInformationPerfection', { Id: row.id }).then(res => {
    listtrace();
  })
}



onMounted(() => {
  
  listtrace();
})


const addNew = () => {
  isEdit.value = false
  dialogTitle.value = '新增商品'
  dialogVisible.value = true

}

const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据刷新成功')
  }, 1000)
}


//修改商品
const updTrace = (row: any) => {
  ruleForm.traceId = row.id
  ruleForm.commodityId = row.commodityId
  ruleForm.productionBatch = row.productionBatch
  ruleForm.shelfLife = row.shelfLife
  ruleForm.licenseNumber = row.licenseNumber
  ruleForm.productionEnterprises = row.productionEnterprises
  ruleForm.coverImage = row.coverImage
  upddialogVisible.value = true;

}

//删除商品
const delTrace = (row: any) => {

  ElMessageBox.confirm(
    '您确定要删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      wirlthttp.post('api/Wirlt/DelTrace', { "traceId": row.id }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          listtrace();
        }
        else {
          ElMessage.error(res.data.message);
        }

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}


//批量删除

const selectedIds = ref([])

const handleSelectionChange = (selection: any) => {
  selectedIds.value = selection.map((item: any) => item.id);
}

const batchDelete = () => {

  if (selectedIds.value.length == 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  ElMessageBox.confirm(
    '您确定要删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      wirlthttp.post('api/Wirlt/ListDelTrace', { "traceId": selectedIds.value }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          selectedIds.value = []
          listtrace();
        }
        else {
          ElMessage.error(res.data.message);
        }

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}



//跳转详情页面
//跳转详情页面
const detail = (row: any) => {
  pinia.trace.Id = row.id
  pinia.trace.CommodityName = row.commodityName
  pinia.trace.ProductionBatch = row.productionBatch
  pinia.trace.ShelfLife = row.shelfLife
  pinia.trace.LicenseNumber = row.licenseNumber
  pinia.trace.ProductionEnterprises = row.productionEnterprises
  pinia.trace.CoverImage = row.coverImage
  router.push('Cultivation')
}



</script>




















<style scoped>
.traceability-list {
  padding: 20px;
  background: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 24px;
  color: #409eff;
}

.page-title h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
  font-weight: 600;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  margin-bottom: 10px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.stat-icon {
  font-size: 40px;
  color: #e1f3ff;
}

.toolbar-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.add-btn {
  background: linear-gradient(135deg, #409eff, #36a3f7);
  border: none;
}

.delete-btn {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border: none;
}

.export-btn {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border: none;
  color: #fff;
}

.refresh-btn {
  background: linear-gradient(135deg, #909399, #a6a9ad);
  border: none;
  color: #fff;
}

.table-card {
  margin-bottom: 20px;
}

.traceability-table {
  margin-bottom: 20px;
}

.column-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-input {
  width: 100%;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-name {
  font-weight: 500;
}

.completeness-tag {
  margin-top: 5px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
}

.pagination-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.total-info {
  color: #606266;
  font-weight: 500;
}

.pagination-right {
  display: flex;
  align-items: center;
}

.form-container {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .traceability-list {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .statistics-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 15px;
  }
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>